<?php
namespace app\index\controller;

use app\index\model\Sign;
use app\index\model\User as UserModel;
use think\Controller;
use think\Db;
use think\Loader;

class User extends Common
{
    public function home()
    {
        var_dump(input('uid'));
    }
	public function index()
    {
        $this->assign('title','用户中心');
        return $this->fetch();
    }
    public function set()
    {
        if(!session('user')){
            $this->success("还没有登录 ,请先登录",url('index/login/index'));
        }
        $this->assign('title','基本设置');
        return $this->fetch();
    }

     public function post()
    {

        $this->assign('title','我的帖子');
        return $this->fetch();
    }

    public function save()
    {
        $data = input('post.');

        $data['user_id'] = session('user')->user_id;

        $validate = Loader::validate('User');

        if(!$validate->scene('save')->check($data)){

            $this->error($validate->getError());
        }

        $res = UserModel::where('user_id', session('user')->user_id)->update($data);

        (new UserModel)->refresh();

        if($res){
            $this->success("修改成功");
        }else{
            $this->error('修改失败，请稍后再试');
        }
    }

    public function upload()
    {
        $file = request()->file('file');
    
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->validate(['size'=>1567800,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){

                $face = 'uploads/'.date("Ymd")."/".$info->getFilename();

                $res = UserModel::where('user_id', session('user')->user_id)->update(['face'=>$face]);

                (new UserModel)->refresh();
                
                if($res){
                    $this->success("上传成功");
                }else{
                    $this->error('上传失败，请稍后再试');
                }
            }else{
                $this->error($file->getError());
                // 上传失败获取错误信息
            }
        }
    }

    public function sign()
    {

        $signInfo = (new Sign)->getSignInfo();

        if($signInfo['is_sign']){
            $this->error('不能重复签到');
        }

        $sign = Sign::where('user_id',session('user')->user_id)->find();

        if($sign){
            $sign->sign_time = time();
            $sign->sign_num = $signInfo['num']+1;
            $res = $sign->save();
        }else{
            $res = Sign::create(['user_id'=>session('user')->user_id,'sign_time'=>time(),'sign_num'=>$signInfo['num']+1]);
        }


       if($res){
            Db::name('user')->where('user_id',session('user')->user_id)->setInc('kiss', $signInfo['kiss']);
            
            $this->success("签到成功");
       }else{
            $this->error('签到失败');
       }
    }
}
